//
//  configFiveVC.m
//  tcpoctest
//
//  Created by gump on 12/14/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "configFiveVC.h"
#import "imageTransfrom.h"
#import "SDSegmentedControl.h"
#import "UIImage+KIAdditions.h"
#import "UIButton+Curled.h"

#import "FirendCircleDataSource.h"
#import "bigHeadImageDataSource.h"

@interface configFiveVC ()

@end

@implementation configFiveVC

enum SetPhotoType
{
    SPT_HEAD,
    SPT_FIRCIRBG,
    SPT_NULL,
};

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        coverIndex = 1;
        buttonArray = [[NSMutableArray alloc]init];
        bsetheadimage = false;
        iSetPhotoIndex = SPT_NULL;
    }
    return self;
}

-(void)dealloc
{
    
    //[selIcon release];
    selIcon = nil;
    
    [buttonArray removeAllObjects];
    //[buttonArray release];
    buttonArray = nil;
}

-(void)initUI
{    
    [self createTitle];
    self.mtitle.text = [NSString stringWithFormat:@"注册%@",T_PROJECTNAME];
    
    UIBarButtonItem *backItem = [self createBarButtonItemWithTitle:@"上一步" target:self action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    //[backItem release];
    
    UIBarButtonItem *nextItem = [self createBarButtonItemWithTitle:@"下一步" target:self action:@selector(nextButtonPressed)];
    self.navItem.rightBarButtonItem = nextItem;
    
    UIImage *backgroundImage = [UIImage imageNamed:@"cover1.jpg"];
    [[DataControl shareControl].fircirDS SetBGImage:
     [backgroundImage transformWidth:BIG_HEAD_IMAGE height:BIG_HEAD_IMAGE]];
    CGRect backgroundRect = CGRectMake(0, 0, self.view.frame.size.width, backgroundImage.size.height);
    backgroundImageView = [[UIImageView alloc] initWithFrame:backgroundRect];
    backgroundImageView.image = backgroundImage;
    backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    backgroundImageView.userInteractionEnabled = YES;
    
    CGRect foregroundRect;
    if (iPhone5) {
        foregroundRect = CGRectMake(0, 0, self.view.frame.size.width, 300.0f);
    }else{
        foregroundRect = CGRectMake(0, 0, self.view.frame.size.width, 230.0f);
    }
    
    UIView *foregroundView = [[UIView alloc]initWithFrame:foregroundRect];
    foregroundView.backgroundColor = [UIColor colorWithRed:245.f/255.f green:245.f/255.f blue:245.f/255.f alpha:1.f];

    
    parallaxView = [[MDCParallaxView alloc] initWithBackgroundView:backgroundImageView
                                                                     foregroundView:foregroundView];
    parallaxView.frame = CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height);
    parallaxView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    parallaxView.backgroundHeight = 250.0f;
    parallaxView.scrollViewDelegate = self;
    [self.view addSubview:parallaxView];
    
    headIV = [[UIImageView alloc]initWithFrame:CGRectMake(18, 69, 58, 58)];
    headIV.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTouch =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pressHeadSet)];
    [headIV addGestureRecognizer:singleTouch];
    
    [self updatePlayerHeadImage:[UIImage imageNamed:@"default_head.png"]];
    
    imageLayer = [CALayer layer];
    imageLayer.cornerRadius = 16.0;
    [self.view.layer addSublayer:imageLayer];
    imageLayer.borderWidth=4.0;
    imageLayer.borderColor = [UIColor whiteColor].CGColor;
    float  heightOfImageLayer = floorf(62);
    imageLayer.cornerRadius = heightOfImageLayer/2.0f;
    imageLayer.frame = CGRectMake(16, 67, 62, 62);
    
    [self.view addSubview:headIV];
    //[headIV release];
    
    for (int btnCnt = 0; btnCnt < 6; btnCnt++) {
        
        float btnY;
        int index;
        if (btnCnt < 3) {
            
            if (iPhone5) {
                btnY = 20;
            }else{
                btnY = 2;
            }
            
            index = btnCnt;
        }else{
            if (iPhone5) {
                btnY = 105;
            }else{
                btnY = 87;
            }
            index = btnCnt - 3;
        }
        
        UIImage *btnImg;
        if (btnCnt == 0) {
            btnImg = [UIImage imageNamed:@"takephoto.png"];
        }else{
            NSString * imgName = [NSString stringWithFormat:@"cover%d.jpg",btnCnt];
            btnImg = [UIImage imageNamed:imgName];
        }
        UIButton *selCoverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        selCoverBtn.tag = btnCnt;
        selCoverBtn.frame = CGRectMake(23 * (index + 1) + 75 * index, btnY, 75, 75);
        [selCoverBtn setContentMode:UIViewContentModeScaleToFill];
        [selCoverBtn setImage:btnImg borderWidth:5.0 shadowDepth:10.0 controlPointXOffset:30.0 controlPointYOffset:70.0 forState:UIControlStateNormal];
        [selCoverBtn addTarget:self action:@selector(selCoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [foregroundView addSubview:selCoverBtn];
        [buttonArray addObject:selCoverBtn];
    }
    
    selIcon = [[UIImageView alloc]initWithFrame:CGRectMake(48, 48, 22, 22)];
    selIcon.image = [UIImage imageNamed:@"icon_cover_sel.png"];
    UIButton *tempButton = [buttonArray objectAtIndex:1];
    [tempButton addSubview:selIcon];
    
}

#pragma mark -private fun-

- (void)updatePlayerHeadImage:(UIImage*)headImg
{
    UIImage *finalImage = nil;
    UIGraphicsBeginImageContext(headImg.size);
    {
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGAffineTransform trnsfrm = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(1.0, -1.0));
        trnsfrm = CGAffineTransformConcat(trnsfrm, CGAffineTransformMakeTranslation(0.0, headImg.size.height));
        CGContextConcatCTM(ctx, trnsfrm);
        CGContextBeginPath(ctx);
        CGContextAddEllipseInRect(ctx, CGRectMake(0.0, 0.0, headImg.size.width, headImg.size.height));
        CGContextClip(ctx);
        CGContextDrawImage(ctx, CGRectMake(0.0, 0.0, headImg.size.width, headImg.size.height), headImg.CGImage);
        finalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    headIV.image = finalImage;
}

-(void)selCoverBtnClick:(id)sender
{
    [selIcon removeFromSuperview];
    UIButton *btn = (UIButton*)sender;
    coverIndex = btn.tag;
    if (btn.tag == 0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"设置朋友圈背景"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"照相机",@"我的相册", nil];
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        actionSheet.tag = 1;
        [actionSheet showInView:self.view];
        
        iSetPhotoIndex = SPT_FIRCIRBG;
    }else{
        NSString * imgName = [NSString stringWithFormat:@"cover%d.jpg",btn.tag];
        UIButton *tempButton = [buttonArray objectAtIndex:btn.tag];
        [tempButton addSubview:selIcon];
        backgroundImageView.image = [UIImage imageNamed:imgName];
        [[DataControl shareControl].fircirDS SetBGImage:
         [[UIImage imageNamed:imgName] transformWidth:BIG_HEAD_IMAGE height:BIG_HEAD_IMAGE]];
    }
}

-(void)pressHeadSet
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"设置头像"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"照相机",@"我的相册", nil];
    actionSheet.tag = 0;
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.view];
    
    iSetPhotoIndex = SPT_HEAD;
}


#pragma mark - ActionSheetDelegate

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self pressCamera];
    }else if (buttonIndex == 1) {
        [self pressPhoto];
    }
}

-(void)pressCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker=[[UIImagePickerController alloc]init];
        picker.sourceType=UIImagePickerControllerSourceTypeCamera;
        picker.allowsEditing = YES;
        picker.delegate=self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)pressPhoto
{
    UIImagePickerController *picker= [[UIImagePickerController alloc]init];
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing=YES;
    picker.delegate=self;
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)backButtonPressed
{
    [[ViewManager sharedViewManager] backView:self];
}

-(void)nextButtonPressed
{
    if (bsetheadimage)
    {
        [[DataControl shareControl].fircirDS SetISSetBGImage:true];
        [[DataControl shareControl].LCDS addLogicCommand:LC_SENDCONFIG];
        
        [[ViewManager sharedViewManager] showView:VI_DEFAULT
                                 withIsRemoveCurV:false
                                    withDirection:VD_RIGHT];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请上传头像"
                                                        message:@"请上传头像"
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
}

-(void)viewWillHide
{
   
}

-(void)clearUI
{
    [self updatePlayerHeadImage:[UIImage imageNamed:@"default_head.png"]];
    backgroundImageView.image = [UIImage imageNamed:@"cover1.jpg"];
    [[DataControl shareControl].fircirDS SetBGImage:
    [backgroundImageView.image transformWidth:BIG_HEAD_IMAGE height:BIG_HEAD_IMAGE]];
}

#pragma mark UIImagePickerControllerDelegate -
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissModalViewControllerAnimated:YES];
    
    switch (iSetPhotoIndex) {
        case SPT_HEAD:
        {
            [[DataControl shareControl] setHeadImage:[image transformWidth:SMALL_HEAD_IMAGE
                                                                    height:SMALL_HEAD_IMAGE]];
            [[DataControl shareControl].bigHIDS SetUserBigImage:[image transformWidth:BIG_HEAD_IMAGE
                                                                       height:BIG_HEAD_IMAGE]];
            [self updatePlayerHeadImage:[DataControl shareControl].iImage];
            
            bsetheadimage = true;
        }
            break;
            case SPT_FIRCIRBG:
        {
            [[DataControl shareControl].fircirDS SetBGImage:[image transformWidth:BIG_HEAD_IMAGE
                                                                           height:BIG_HEAD_IMAGE]];
            backgroundImageView.image = image;
        }
            break;
        default:
            break;
    }
    
    
    
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


@end
